<?php
/**
 * User: surestdeng
 * Date: 2020/4/4
 * Time: 10:14:15
 */

namespace App\Services\Video;

use App\Models\Video\OperateVideoModel;
use App\Repositories\Video\VideoParseInterface;
use App\Repositories\Video\VideoParseService;
use Illuminate\Support\Arr;

class VideoService
{
    protected $service;

    public function __construct(VideoParseService $service)
    {
        $this->service = $service;
    }

    /**
     * 解析
     * User: surest
     * Date: 2020/4/11
     */
    public function tryParse($url)
    {
        $url = trim($url, '/');
        $data = OperateVideoModel::query()
            ->where('source_url', $url)
            ->first(['id', 'source_url', 'target_url', 'success', 'count', 'img_url', 'title']);

        if($data) {
            $data = $data->toArray();
            OperateVideoModel::query()->where('id', $data['id'])->update(['count' => ++$data['count']]);
            if(Arr::get($data, 'success') == 1) { return $data; }
            return null;
        }

        return $this->parse($url);
    }

    public function parse($url)
    {
        list($success, $data) = $this->service->getData($url);
        if($success) {
            $data['success'] = 1;
            OperateVideoModel::query()->insert($data);
            return $data;
        }else{
            $data['success'] = 0;
            OperateVideoModel::query()->insert($data);
        }
        return null;
    }
}
